#ifndef __SYS_H
#define __SYS_H
#include "air32f10x_conf.h"
#include "printf.h"

#define revert8bit(x) (__RBIT(x)>>(32-8))
// 变量
extern RCC_ClocksTypeDef clocks;
// GPIO初始化结构
typedef struct
{
    GPIO_TypeDef *GPIOx;         // 指向哪个IO口
    GPIO_InitTypeDef GPIO_Param; // 初始化参数
    uint8_t InitValue;           // 初始值
} IOList;

// 位带访问原理:                                 基地址        上移32M字节    字节偏移*32      位偏移 * 4
#define BIT_ADDR(addr, bit) ((addr & 0xF0000000) + 0x2000000 + ((addr & 0xFFFFF) << 5) + (bit << 2))
#define BIT_(addr, bit) *((volatile uint32_t *)(BIT_ADDR(addr, bit)))
#define ODR_OFFSET 12
#define IDR_OFFSET 8
#define PAout(n) BIT_((GPIOA_BASE + ODR_OFFSET), n)
#define PBout(n) BIT_((GPIOB_BASE + ODR_OFFSET), n)
#define PCout(n) BIT_((GPIOC_BASE + ODR_OFFSET), n)
#define PDout(n) BIT_((GPIOD_BASE + ODR_OFFSET), n)
#define PEout(n) BIT_((GPIOE_BASE + ODR_OFFSET), n)
#define PFout(n) BIT_((GPIOF_BASE + ODR_OFFSET), n)
#define PGout(n) BIT_((GPIOG_BASE + ODR_OFFSET), n)
#define PAin(n) BIT_((GPIOA_BASE + IDR_OFFSET), n)
#define PBin(n) BIT_((GPIOB_BASE + IDR_OFFSET), n)
#define PCin(n) BIT_((GPIOC_BASE + IDR_OFFSET), n)
#define PDin(n) BIT_((GPIOD_BASE + IDR_OFFSET), n)
#define PEin(n) BIT_((GPIOE_BASE + IDR_OFFSET), n)
#define PFin(n) BIT_((GPIOF_BASE + IDR_OFFSET), n)
#define PGin(n) BIT_((GPIOG_BASE + IDR_OFFSET), n)

void RCC_ClkConfiguration(void);
void print_system_info();
void _putchar(char character);
void Delay_Init(void);
void gpio_init(IOList *pGPIO_Init_Param);
void Delay_us(uint32_t nus);
uint8_t Delay_us_With_Break_by_Value(uint32_t nus, volatile uint8_t *pValue);
uint8_t Delay_us_with_Break_by_Function(uint32_t nus, uint8_t(fun(void)));
uint8_t read_swd_jump_states();
uint8_t read_extra_jump_states();


__STATIC_FORCEINLINE void Delay_ms(uint16_t nms)
{
    Delay_us(nms * 1000);
}

__STATIC_FORCEINLINE void add_1_per_1ms(uint32_t *count)
{
    if (SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk)
    {
        (*count)++;
    }
}

#endif
